package com.bhs.sansonglogistics.ui.order;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.ImageReturn;
import com.bhs.sansonglogistics.bean.PictureBean;
import com.bhs.sansonglogistics.bean.event.RefreshOrder;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.PictureSelectAdapter;

import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 签收 上传回单
 */
public class SignForActivity extends BaseActivity implements View.OnClickListener, NetCallBack {

    private TextView mTvTitle;
    private TextView mTvWay;
    private RecyclerView mRvList;
    private PictureSelectAdapter adapter;
    private String deliver_sn;
    private Button mBtnSubmit;
    private String path;
    private TextView mTvSignature;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private String sign_img;
    private int type;
    private ConstraintLayout mClSignature;
    private TextView mTvType;

    @Override
    public int initLayout() {
        return R.layout.activity_sign_for;
    }

    @Override
    public void initView() {
        path=getExternalCacheDir().getPath()+ "/"+System.currentTimeMillis()+".png";
        deliver_sn=getIntent().getStringExtra("deliver_sn");
        type=getIntent().getIntExtra("type",1);
        mTvTitle = findViewById(R.id.tv_title);
        mTvWay = findViewById(R.id.tv_way);
        mRvList = findViewById(R.id.rv_list);
        mTvWay.setOnClickListener(this);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mTvSignature = findViewById(R.id.tv_signature);
        mTvSignature.setOnClickListener(this);
        mClSignature = findViewById(R.id.cl_signature);
        mTvType = findViewById(R.id.tv_type);
        if(type==2){
            mClSignature.setVisibility(View.GONE);
            mTvType.setText("上传回单照片");
            mTvTitle.setText("上传回单");
            mBtnSubmit.setText("确认上传");
        }

    }

    @Override
    public void initData() {
        mTvTitle.setText("签收");
        adapter=new PictureSelectAdapter(9,this);
        mRvList.setAdapter(adapter);
        mRvList.setLayoutManager(new GridLayoutManager(mContext,3));

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                uploadImage();
            }
        });
    }

    private void uploadImage() {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File(path);
        if(!file.exists()) {
            return;
        }
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("file", file.getName(), imageBody);
        builder.addFormDataPart("upload_file", "customer");
        builder.addFormDataPart("type", "app");
        List<MultipartBody.Part> parts = builder.build().parts();
        networkRequest(netApi.imageUpload(parts), this,9527);
    }


    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.tv_signature){
            Intent intent = new Intent(this, ElectronicSignatureActivity.class);
            intent.putExtra("path",path);
            intentActivityResultLauncher.launch(intent);
        }else if(view.getId()==R.id.btn_submit){
            if(type==1) {
                if (TextUtils.isEmpty(adapter.getImages())) {
                    ToastUtil.show("请上传签收凭证");
                    return;
                }
                if (TextUtils.isEmpty(sign_img)) {
                    ToastUtil.show("请签电子签名");
                    return;
                }
                networkRequest(netApi.confirmSing(deliver_sn, adapter.getImages(), sign_img), this);
            }else {
                if (TextUtils.isEmpty(adapter.getImages())) {
                    ToastUtil.show("请上传回单照片");
                    return;
                }
                networkRequest(netApi.uploadReceipt(deliver_sn, adapter.getImages()), this);
            }
        }
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if(requestCode==9527){
            ImageReturn dataBean = new Gson().fromJson(json, ImageReturn.class);
            if (dataBean.isStatus()) {
               sign_img=dataBean.getData().getSrc();
                Glide.with(this)
                        .asBitmap()
                        .load(sign_img)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                Drawable drawable = new BitmapDrawable(resource);
                                mTvSignature.setBackground(drawable);
                                mTvSignature.setText("");
                            }

                        });
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        }else {
            BaseBean dataBean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(dataBean.getMsg());
            if(dataBean.isStatus()){
                finish();
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }



}